package database

import (
	"stacks/config"

	"github.com/redis/go-redis/v9"
	"github.com/sirupsen/logrus"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var DB *gorm.DB
var RDB *redis.Client

func InitDB(cfg *config.Config) error {
	dsn := cfg.DSN()
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		return err
	}

	// 注册全局钩子
	registerHooks(db)

	DB = db
	return nil
}

func registerHooks(db *gorm.DB) {
	// 查询钩子
	err := db.Callback().Query().After("gorm:query").Register("log_query_error", func(db *gorm.DB) {
		if db.Error != nil {
			logrus.WithFields(logrus.Fields{"operation": "query", "error": db.Error}).Error("Database operation failed")
		}
	})
	if err != nil {
		logrus.WithFields(logrus.Fields{"operation": "register_query_hook", "error": err}).Error("Failed to register query hook")
	}

	// 更新钩子
	err = db.Callback().Update().After("gorm:update").Register("log_update_error", func(db *gorm.DB) {
		if db.Error != nil {
			logrus.WithFields(logrus.Fields{"operation": "update", "error": db.Error}).Error("Database operation failed")
		}
	})
	if err != nil {
		logrus.WithFields(logrus.Fields{"operation": "register_update_hook", "error": err}).Error("Failed to register update hook")
	}

	// 删除钩子
	err = db.Callback().Delete().After("gorm:delete").Register("log_delete_error", func(db *gorm.DB) {
		if db.Error != nil {
			logrus.WithFields(logrus.Fields{"operation": "delete", "error": db.Error}).Error("Database operation failed")
		}
	})
	if err != nil {
		logrus.WithFields(logrus.Fields{"operation": "register_delete_hook", "error": err}).Error("Failed to register delete hook")
	}

	// 创建钩子
	err = db.Callback().Create().After("gorm:create").Register("log_create_error", func(db *gorm.DB) {
		if db.Error != nil {
			logrus.WithFields(logrus.Fields{"operation": "create", "error": db.Error}).Error("Database operation failed")
		}
	})
	if err != nil {
		logrus.WithFields(logrus.Fields{"operation": "register_create_hook", "error": err}).Error("Failed to register create hook")
	}
}

func InitRedis(cfg *config.Config) error {
	client := redis.NewClient(&redis.Options{
		Addr:     cfg.Redis.Addr,
		Password: cfg.Redis.Password,
		DB:       cfg.Redis.DB,
	})

	RDB = client
	return nil
}

// GetDB 获取带租户过滤器和逻辑删除过滤器的数据库实例（默认使用）
func GetDB() *gorm.DB {
	// 使用Session模式，避免过滤器重复应用
	return WithTenantFilter(WithSoftDeleteFilter(DB.Session(&gorm.Session{})))
}

// GetRawDB 获取原始数据库实例（跳过所有过滤器）
func GetRawDB() *gorm.DB {
	return DB
}

// GetDBWithSoftDeleteOnly 获取仅带逻辑删除过滤器的数据库实例
func GetDBWithSoftDeleteOnly() *gorm.DB {
	return WithSoftDeleteFilter(DB)
}

// GetDBWithTenantOnly 获取仅带租户过滤器的数据库实例
func GetDBWithTenantOnly() *gorm.DB {
	return WithTenantFilter(DB)
}

func GetRedis() *redis.Client {
	return RDB
}
